# Maps.py: maps module
# 22/06/09
# Copyright(c) 2009 Victor Freire e Cassio Espindola. All rights reserved.
# Python 2.6.2

import pygame
import os
import string
import copy
import Shared


class MapsClass:
    def __init__(self):
        self.DEFAULT_PATH = os.path.join(os.curdir, "data", "maps")
        self.maps = {}
        self.world = None
        self.world_bounds = (0, 0)
    
    
    def load_maps(self):
        for roots, dirs, files in os.walk(self.DEFAULT_PATH):
            for map_name in files:
                if map_name[-3:] == 'dat':
                    try:
                        world = []
                        f = open(os.path.join(self.DEFAULT_PATH,map_name),'r')
                        content = f.readlines()
                        for line in content:
                            line = string.replace(line,"\n","")
                            line = list(line)
                            world.append(line)
                        self.maps[map_name] = copy.deepcopy(world)
                    except:
                        print "Unable to open the map file - %s" % f
    
    
    def get_map(self, map_name):
        try:
            return self.maps[map_name]
        except:
            print "Fatal Error on loading map - %s" % map_name #unrecoverable error
            raise SystemExit
    
       
    def set_current_map(self, map_name):
        ''' Sets the map to be played. '''
        self.world = self.get_map(map_name)
        self.world_bounds = (len(self.world[0]), len(self.world))
    
        
    def wall_onG(self, gridpos):
        ''' Checks if there is a wall on given grid coordinates. '''
        return self.world[gridpos[1]][gridpos[0]] != '0'
        
            
    def wall_onU(self, pos):
        ''' Checks if there is a wall on given unit coordinates. '''
        gridpos = Shared.togridF(pos)
        return self.world[gridpos[1]][gridpos[0]] != '0'
    
    def is_valid_unit(self, unitpos):
        ''' Is the unit coordinates passed valid? '''
        return self.is_valid_grid(Shared.togridF(unitpos))
    
    def is_valid_grid(self, gridpos):
        ''' Is the grid passed valid? '''
        return 0 <= gridpos[0] < self.world_bounds[0] and 0 <= gridpos[1] < self.world_bounds[1]
                

Maps = MapsClass()


